package com.smasher.print.dw;

import android.text.TextUtils;

import com.smasher.print.core.PrintField;
import com.smasher.print.core.PrintTemplate;
import com.smasher.print.dw.template.DWPrintField;
import com.smasher.print.dw.template.DWPrintTemplate;
import com.smasher.print.dw.template.TemplatePrintFactory;

import org.json.JSONObject;

import java.io.IOException;

import dw.printer.CmdManager;
import dw.printer.Printer;

public class PrintContent {

    public static final String TAG = "PrintContent";

    private final Printer printer;

    public PrintContent(Printer printer) {
        this.printer = printer;
    }


    public void printText(JSONObject json) {

        PrintTemplate templateTemp = TemplatePrintFactory.createBryDbTemplate(json);

        DWPrintTemplate template = (DWPrintTemplate) templateTemp;

        try {
            CmdManager manager = printer.cmdManager.initPrinter();

            // 打印标题
            if (template.getTitle() != null) {
                manager.setBold(template.isTitleBold())
                        .setAlign(template.getTitleAlign())
                        .setText(template.getTitle() + "\n")
                        .printAndFeedLines(template.getTitleGap());
            }

            // 打印各个字段
            if (template.getFields() != null) {
                for (PrintField fieldTemp : template.getFields()) {
                    if (fieldTemp instanceof DWPrintField) {
                        DWPrintField field = (DWPrintField) fieldTemp;
                        String value = field.getValue();
                        int gap = field.getGap();
                        // 只有当值不为空时才打印
                        if (!TextUtils.isEmpty(value)) {
                            manager.setAlign(field.getAlign())
                                    .setBold(field.isBold())
                                    .setText(field.getLabel() + value + "\n");

                            if (gap > 0) {
                                manager.printAndFeedLines(gap);
                            }
                        }
                    }

                }
            }

            // 打印页脚
            if (template.getFooter() != null) {
                manager.printAndFeedLines(2);
                manager.setBold(false)
                        .setAlign(template.getFooterAlign())
                        .setText(template.getFooter() + "\n")
                        .printAndFeedLines(template.getFooterGap())
                        .printAndFeedDots(template.getFooterDots());
            }

            manager.print();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
